import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:megatron/apis.dart';
import 'package:megatron/bean/videobean.dart';
import 'package:megatron/utils/fluro.dart';
import 'package:megatron/utils/mydio.dart';
import 'package:megatron/utils/utils.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../const.dart';
import '../routes.dart';

class MainPage extends StatefulWidget {
  @override
  _MainPageState createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> {
  SharedPreferences sp;
  String token;
  List<VideoBean> items = List();
  bool isPush = false;
  var url;
  var _scaffoldkey = new GlobalKey<ScaffoldState>();

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    isPush = true;
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getToken();
    Const.jumpPlugin.setMethodCallHandler(platformCallHandler);
  }

  // android 发送到 flutter
  Future<dynamic> platformCallHandler(MethodCall call) async {
    switch (call.method) {
      case 'android':
        print('!!!!!!!!!!${call.arguments}');
        if ('onStart' == call.arguments) {
          isPush = true;
        } else if ('onStop' == call.arguments) {
          isPush = false;
          //重新获取列表
          items.clear();
          video(token);
        }
        setState(() {});
        return call.arguments;
        break;
    }
  }

  getToken() async {
    sp = await SharedPreferences.getInstance();
    token = sp.getString('token');
    video(token);
  }

  video(String token) {
    Map map = Map<String, String>();
    map['page'] = '0';
    map['size'] = '99';
    MyDio.getInstance().clearInstance();
    print(token);
    MyDio.getInstance(token: token).get(Apis.video, (data) async {
      print(data);
      int totalElements = data['totalElements'];
      if (totalElements != 0) {
        for (var s in data['content']) {
          VideoBean videoBean = VideoBean.fromJson(s);
          items.add(videoBean);
        }
      }
      setState(() {});
    }, errorCallBack: (error) async {
      if (error == 401) {
        sp.clear();
        Routes.router.navigateTo(context, '${Routes.login}',
            clearStack: true, transition: TransitionType.fadeIn);
      }
    }, params: map);
  }

  Future<Null> startPush() async {
    var rotation = sp.get('rotation');
    if (rotation == null) {
      rotation = 0;
    }
    var screen = sp.get('screen');
    if (screen == null) {
      screen = 0;
    }
    Map<String, dynamic> map = {
      'url': '${Const.PUSHURL}$url',
      'rotation': rotation,
      'screen': screen,
    };
    await Const.jumpPlugin.invokeMethod('oneAct', map);
  }

  Future<Null> _onRefresh() async {
    items.clear();
    await video(token);
    return;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        key: _scaffoldkey,
        floatingActionButton: Padding(
          padding: const EdgeInsets.symmetric(vertical: 72, horizontal: 20),
          child: IconButton(
            onPressed: () {
              if (isPush) {
                Const.jumpPlugin.invokeMethod('onStop');
              } else {
                startPush();
                /*MyDio.getInstance(token: token).post(Apis.addVideo,
                    (data) async {
                  url = data['id'];
                  startPush();
                }, errorCallBack: (error) async {
                  if (error == 401) {
                    sp.clear();
                    Routes.router.navigateTo(context, '${Routes.login}',
                        clearStack: true, transition: TransitionType.fadeIn);
                  }
                });*/
              }
            },
            iconSize: 77,
            icon: isPush
                ? Image.asset('images/home_btn_stop.png')
                : Image.asset('images/home_btn_record.png'),
          ),
        ),
        appBar: AppBar(
          centerTitle: true,
          title: Text(
            '图传系统',
            style: TextStyle(fontSize: 18),
          ),
          actions: <Widget>[
            IconButton(
              icon: Image.asset(
                'images/home_btn_set_up.png',
                scale: 3,
              ),
              onPressed: () {
                if (isPush) {
                  Utils.getInstance().showSnackBar(_scaffoldkey, '传送中,无法更改设置');
                  return;
                }
                Routes.router.navigateTo(context, '${Routes.setting}',
                    replace: false, transition: TransitionType.fadeIn);
              },
            ),
          ],
        ),
//      body: NullContainer(),
        body: RefreshIndicator(
          onRefresh: _onRefresh,
          child: items.length == 0 ? NullContainer() : VideoList(data: items),
        )
//      body: VideoList(),
        );
  }
}

class NullContainer extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        children: <Widget>[
          SizedBox(
            height: 134,
          ),
          Image.asset(
            'images/home_pic_nothing.png',
            scale: 3,
          ),
          SizedBox(
            height: 20,
          ),
          Text(
            '暂无视频信息\n点击开始视频传送',
            style: TextStyle(color: Const.gray, fontSize: 16),
            textAlign: TextAlign.center,
          )
        ],
      ),
    );
  }
}

class VideoList extends StatelessWidget {
  final data;

  const VideoList({Key key, this.data}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.fromLTRB(12, 12, 6, 0),
      child: ListView(
        children: <Widget>[
          ListItem(data: data),
        ],
      ),
    );
  }
}

class ListItem extends StatelessWidget {
  final data;

  const ListItem({Key key, this.data}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    _setNavigations() {
      List<Widget> list = List();
      for (VideoBean videoBean in data) {
        list.add(GestureDetector(
          onTap: () {
            Routes.router.navigateTo(context,
                '${Routes.videoplay}?id=${videoBean.id}&size=${videoBean.size}&length=${videoBean.length}&creatorDeptName=${FluroConvertUtils.fluroCnParamsEncode(videoBean.creatorDeptName)}&creatorName=${FluroConvertUtils.fluroCnParamsEncode(videoBean.creatorName)}&createDate=${FluroConvertUtils.fluroCnParamsEncode(videoBean.createDate)}',
                replace: false, transition: TransitionType.fadeIn);
          },
          child: Container(
            margin: const EdgeInsets.fromLTRB(0, 0, 6, 5),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.all(Radius.circular(5)),
              image: DecorationImage(
                fit: BoxFit.fill,
                image: Utils.getInstance().checkEmpty(videoBean.coverPath)
                    ? ExactAssetImage('images/items.png')
                    : NetworkImage(
                        '${Const.BASEURL}${videoBean.coverPath}',
                      ),
              ),
            ),
            child: Icon(
              Icons.play_arrow,
              size: 55,
              color: const Color(0x80000000),
            ),
//            child: Image.asset(
//              'images/home_icon_play.png',
//              scale: 2,
//              color: Const.blue,
//            ),
//            child: Container(
//              alignment: Alignment.bottomCenter,
//              child: SizedBox(
//                height: 35,
//                width: MediaQuery.of(context).size.width,
//                child: Container(
//                  decoration: BoxDecoration(
//                    color: const Color(0x80000000),
//                    borderRadius:
//                        BorderRadius.vertical(bottom: Radius.circular(5)),
//                  ),
//                  child: Image.asset(
//                    'images/home_icon_play.png',
//                    scale: 2,
//                  ),
////                  child: Image.asset(
////                    'images/home_icon_play.png',
////                    scale: 4,
////                  ),
////                  child: Row(
////                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
////                    children: <Widget>[
////                      Row(
////                        mainAxisAlignment: MainAxisAlignment.start,
////                        children: <Widget>[
////                          SizedBox(
////                            width: 4,
////                          ),
////                          Text(
////                            '00:20',
////                            style: TextStyle(fontSize: 12, color: Colors.white),
////                          ),
////                          Padding(
////                            padding: const EdgeInsets.symmetric(
////                                horizontal: 5, vertical: 5),
////                            child: Container(
////                              width: 1,
////                              color: Colors.white,
////                            ),
////                          ),
//////                          Text(
//////                            '12.3MB',
//////                            style: TextStyle(fontSize: 12, color: Colors.white),
//////                          ),
////                        ],
////                      ),
//////                      Row(
//////                        children: <Widget>[
//////                          Image.asset(
//////                            'images/home_icon_play.png',
//////                            scale: 4,
//////                          ),
//////                          SizedBox(
//////                            width: 4,
//////                          ),
//////                        ],
//////                      ),
////                    ],
////                  ),
//                ),
//              ),
//
////          child: Row(children: <Widget>[
////            Text('00:20', style: TextStyle(fontSize: 12, color: Colors.white),),
////            Container(width: 1, color: Colors.white,),
////            Text(
////              '12.3MB', style: TextStyle(fontSize: 12, color: Colors.white),),
////            Image.asset('images/home_icon_play.png', scale: 3,)
////          ],
////          ),
//            ),
          ),
        ));
      }
      return list;
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        SizedBox(
          height: 5,
        ),
        Text(
          '2020年01月11日',
          style: TextStyle(fontSize: 20, color: Const.gray66),
        ),
        SizedBox(
          height: 5,
        ),
        GridView.count(
          // 禁止滚动
          physics: NeverScrollableScrollPhysics(),
          shrinkWrap: true,
          childAspectRatio: 2 / 3,
          //横轴数量 这里的横轴就是x轴 因为方向是垂直的时候 主轴是垂直的
          crossAxisCount: 3,
          padding: const EdgeInsets.all(0),
          //主轴间隔
          mainAxisSpacing: 2,
          //横轴间隔
          crossAxisSpacing: 2,
          children: _setNavigations(),
        )
      ],
    );
  }
}
